from PySide6.QtCore import QAbstractTableModel, Qt, QEvent
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QStyledItemDelegate, QApplication, QStyleOptionButton, QStyle


class CertificatesListModel(QAbstractTableModel):
    def __init__(self, data=None):
        super().__init__()
        self._data = data or []
        self._headers = ["存单ID", "用户ID", "存单内容","创建时间", "存单状态", "操作"]
        self._keys = ["id", "member_id", "certificates","created_at" ,"certificates_status", "model_config", ""]

    def rowCount(self, parent=None):
        return len(self._data)

    def columnCount(self, parent=None):
        return len(self._headers)

    def data(self, index, role=Qt.DisplayRole):
        """检查data"""
        if not index.isValid():
            return None
        row = index.row()
        col = index.column()
        value = self._data[row].get(self._keys[col], "")
        if role == Qt.DisplayRole:
            if self._keys[col] in ["created_at"] and value:
                value = value.strftime("%Y-%m-%d %H:%M:%S")
                return value
            return str(value)
        elif role == Qt.TextAlignmentRole:
            # 数字类字段右对齐
            if self._keys[col] in ["id", "member_id", "amount"]:
                return Qt.AlignRight | Qt.AlignVCenter
            else:
                return Qt.AlignCenter | Qt.AlignVCenter
        elif role == Qt.BackgroundRole:
            # 检测状态列是否为已退款，整行变色
            status_value = self._data[row].get("certificates_status", "")
            if status_value == "待消费":
                return QColor("#BCCDF1")  # 浅蓝色，可以改成灰色等
        return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        """
        设置表头，行头
        :param section: 表示“第几个”，从 0 开始
        :param orientation:Qt.Horizontal → 问的是列头（表格上方） Qt.Vertical → 问的是行头（表格左侧）
        :return:
        """
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return self._headers[section]
            else:
                return str(section + 1)
        return None

    def update_data(self, new_data):
        """刷新数据"""
        self.beginResetModel()
        self._data = new_data
        self.endResetModel()


class CertificatesConsumption(QStyledItemDelegate):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.consume_callback = None

    def _should_show_refund_button(self, model, row):
        type_index = model.index(row, 4)
        trans_type = model.data(type_index)
        return trans_type == "待消费"

    def paint(self,painter, option, index):
        if index.column() == 5:
            if self._should_show_refund_button(index.model(), index.row()):
                style_option = QStyleOptionButton()
                style_option.rect = option.rect.adjusted(2, 2, -2, -2)
                style_option.text = "消费"
                style = QApplication.style()
                style.drawControl(QStyle.CE_PushButton, style_option, painter)
                return
        super().paint(painter, option, index)

    def editorEvent(self, event, model, option, index):
        if index.column() != 5:
            return False
        if not self._should_show_refund_button(model, index.row()):
            return False
        if event.type() == QEvent.MouseButtonRelease and event.button() == Qt.LeftButton:
            row = index.row()
            if self.consume_callback:
                self.consume_callback(row)  # ✅ 传出行号！
            return True  # 事件已处理
        return False
